<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/19
 * Time: 9:41
 */

namespace App\Http\Controllers\Home;

use App\Model\Address;
use App\Model\Banner;
use App\Model\CaseClassify;
use App\Model\Categorys;
use App\Model\Factory;
use App\Model\ShopGoods;
use App\Model\ShopGoodsClassify;
use App\Model\Token;
use App\Model\Tutor;
use App\Model\VideoCase;
use extend\api\HttpClient;
use Illuminate\Http\Request;
use Session;

class IndexController
{
    /**
     * 前台首页
     */
    public function index()
    {

    }

    /**
     * 前端底部数据
     * @return array
     */
    public function classify()
    {
        $rico = ShopGoodsClassify::where(['enabled' => 1, 'pid' => 3])->get()->toArray();

//        foreach ($rico as $k =>$v){
//            $rico[$k]['tow_data']=ShopGoodsClassify::where( ['pid' => $v['id'] ] )->get()->toArray();
//        }

        if ($rico) {
            return ['code' => 1, 'data' => $rico];
        }
        return ['code' => 0, 'data' => '没有数据'];
    }

    /**
     * 分类查询商品
     * @param Request $request
     */
    public function category(Request $request)
    {
        $data = $request->all();
        switch ($data['class']) {
            case 'select'://查询商城下所有分类数据
                $category = ShopGoodsClassify::where(['pid' => 7, 'enabled' => 1])->get()->toArray();
                if (!empty($category)) {
                    return ['code' => 1, 'data' => $category];
                } else {
                    return ['code' => 0, 'data' => '暂无分类,请后台手动添加'];
                }
                break;
            case 'find'://查询当前分类下所有商品
                $goods = ShopGoods::where(['two_tid' => $data['cid'], 'status' => 1, 'type' => 1])->paginate(6);
                if ($goods) {
                    return ['code' => 1, 'data' => $goods];
                } else {
                    return ['code' => 0, 'data' => '该分类下暂无商品'];
                }
                break;

        }
    }

    /**
     * 商品搜索框
     * @return array
     */
    public function searchBox(Request $request)
    {

        $cid = $request->input('cid');
        $keyword = $request->input('keyword');
        $categoryId = [];
        $categoryData = ShopGoodsClassify::where(['pid' => $cid, 'enabled' => 1])->select('id')->get()->toArray();
        $categoryId[] = $cid;
        foreach ($categoryData as $k => $v) {
            $categoryId[] = $v['id'];
        }
        if (empty($cid)) {
            $goods = ShopGoods::where(['status' => 1, 'type' => 1, 'is_throw' => 0, 'is_brand' => 1])->where('goodsname', 'like', '%' . $keyword . '%')->paginate(6);
        } else {
            $goods = ShopGoods::where(['status' => 1, 'type' => 1, ''])->where('goodsname', 'like', '%' . $keyword . '%')->paginate(6);
        }

        if ($goods) {
            return ['code' => 1, 'data' => $goods];
        } else {
            return ['code' => 0, 'data' => '暂无符合条件的商品'];
        }
    }

    /**
     * 首页轮播图
     */
    public function banner()
    {
        $bannerData = Banner::where('type', 1)->select('banner_img')->get()->toArray();
        if ($bannerData) {
            return ['code' => 1, 'data' => $bannerData];
        } else {
            return ['code' => 0, 'data' => '暂无数据'];
        }
    }

    /**
     * 首页特价商品分类
     * @return array
     */
    public function index_classify(Request $request)
    {
        $data = $request->all();
        $ClassifyModel = new ShopGoodsClassify();
        //折扣专区id
        $classify = $ClassifyModel->where(['enabled' => 1, 'pid' => $data['cid']])->orderBy('displayorder')->get()->toArray();
        if ($classify) {
            return ['code' => 1, 'data' => $classify];
        } else {
            return ['code' => 0, 'data' => '暂无分类'];
        }
    }

    /**
     * @param Request $request
     * 获取分类下商品数据
     */
    public function getShopGoods(Request $request)
    {
        $cid = $request->input('id');
        if (empty($cid)) {
            $goodsList = ShopGoods::where(['cid' => 3, 'type' => 1, 'status' => 1, 'is_throw' => 0, 'is_brand' => 1])->orderby('id', 'DESC')->get()->toArray();
            if (empty($goodsList)) {
                $goodsList = ShopGoods::where(['cid' => 3, 'type' => 1, 'status' => 1, 'is_throw' => 0])->orderby('id', 'DESC')->get()->toArray();
            }
        } else {
            $goodsList = ShopGoods::where(['two_tid' => $cid, 'type' => 1, 'status' => 1, 'is_throw' => 0, 'is_brand' => 1])->get()->orderby('id', 'DESC')->toArray();
            if (empty($goodsList)) {
                $goodsList = ShopGoods::where(['two_tid' => $cid, 'type' => 1, 'status' => 1, 'is_throw' => 0])->orderby('id', 'DESC')->get()->toArray();
            }
        }

        if ($goodsList) {
            return ['code' => 1, 'data' => $goodsList];
        } else {
            return ['code' => 0, 'data' => '暂无商品'];
        }
    }

    /**
     * 首页新人专区
     */
    public function newborn()
    {
        $goodsList = ShopGoods::where(['cid' => 1, 'type' => 1, 'status' => 1])->orderBy('id', 'DESC')->get()->toArray();
        if ($goodsList) {
            return ['code' => 1, 'data' => $goodsList];
        } else {
            return ['code' => 0, 'data' => '暂无商品'];
        }
    }

    /**
     * 首页复销专区
     */
    public function resale(Request $request)
    {
        $data = $request->all();
        $shopModel = new ShopGoods();
        $goodsList = ShopGoods::where(['cid' => 3, 'type' => 1, 'status' => 1])->orderBy('id', 'DESC')->get()->toArray();
        if (empty($goodsList)) {
            return ['code' => 0, 'data' => '暂无商品'];
        } else {
            return ['code' => 1, 'data' => $goodsList];
        }

    }

    public function resale_goods()
    {
        return view('Home.index.resale');
    }

    /**
     * 案例首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function case_index()
    {
        $user = Session::get('home_user');
        if (empty($user)) {
            Session::put('target_url', "/Home/index/case");
            return redirect('/home/excellent/index');// 跳转到首页
        } else {
            return view('Home.index.case');
        }


    }

    /**
     * 获取所有分类
     * @return array
     */
    public function case_classify()
    {
        $caseClassifyModel = new CaseClassify();
        $classify = $caseClassifyModel->orderBy('sort', 'ASC')->get()->toArray();
        if ($classify) {
            return ['code' => 1, 'data' => $classify];
        } else {
            return ['code' => 0, 'data' => '暂无分类'];
        }
    }

    /**
     * 案例搜索页面
     */
    public function search_case()
    {
        return view('Home.index.search_case');
    }

    /**
     * 案例搜索数据
     * @param Request $request
     * @return array
     */
    public function search_result(Request $request)
    {
        $data = $request->all();
        $caseModel = new VideoCase();
        if (empty($data['keyword'])) {
            return ['code' => 0, 'data' => '请输入关键字'];
        }
        $case = $caseModel->where('case_name', 'like', '%' . $data['keyword'] . '%')->get()->toArray();
        if ($case) {
            return ['code' => 1, 'data' => $case];
        } else {
            return ['code' => 0, 'data' => '暂无符合条件的案例'];
        }
    }

    /**
     * 商品分类
     */
    public function top()
    {
        $ClassifyModel = new ShopGoodsClassify();
        //特价专区id
        $classify = $ClassifyModel->where(['enabled' => 1, 'pid' => 7])->orderBy('displayorder', 'ASC')->get()->toArray();
        if ($classify) {
            return ['code' => 1, 'data' => $classify];
        } else {
            return ['code' => 0, 'data' => '暂无分类'];
        }
    }


    /**
     * 获取分类下案例
     * @param Request $request
     * @return array
     */
    public function get_case(Request $request)
    {
        $data = $request->all();
        $caseModel = new VideoCase();
        if ($data['id'] == 19) {
            $case = $caseModel->join('case_classify', 'case_classify.id', '=', 'video_case.cid')->select('video_case.*')->orderBy('video_case.id', 'asc')->get()->toArray();
        } else {
            $case = $caseModel->where('cid', $data['id'])->orderBy('id', 'asc')->get()->toArray();
        }

        if ($case) {
            return ['code' => 1, 'data' => $case];
        } else {
            return ['code' => 0, 'data' => '暂无案例'];
        }
    }

    /**
     *案例详情
     */
    public function case_detail()
    {
        return view('Home.index.case_detail');
    }

    /**
     * 案例详情
     * @param Request $request
     * @return array
     */
    public function getCaseDetail(Request $request)
    {
        $case_id = $request->input('id');
        $caseModel = new VideoCase();
        $detail = $caseModel->where('id', $case_id)->first();
        if ($detail) {
            return ['code' => 1, 'data' => $detail];
        } else {
            return ['code' => 0, 'data' => '参数错误'];
        }
    }

    /**
     * 分类详情页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function sort_detail()
    {
        return view('Home.index.indexDetail');
    }

    /**
     * 分类详情页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function special()
    {
        return view('Home.index.special');
    }

    /**
     * 特价商品
     */
    public function special_list(Request $request)
    {
        $data = $request->all();
        $shopModel = new ShopGoods();
        if (!empty($data['two_tid'])) {
            $shopData = $shopModel->where(['status' => 1, 'type' => 1, 'cid' => $data['cid'], 'two_tid' => $data['two_tid']])->orderby('id', 'DESC')->get()->toArray();
            if (empty($shopData)) {
                return ['code' => 0, 'data' => '暂无商品'];
            } else {
                return ['code' => 1, 'data' => $shopData];
            }
        } else {
            $shopData = $shopModel->where(['status' => 1, 'type' => 1, 'cid' => $data['cid']])->orderby('id', 'DESC')->get()->toArray();
            if (empty($shopData)) {
                return ['code' => 0, 'data' => '暂无商品'];
            } else {
                return ['code' => 1, 'data' => $shopData];
            }
        }
    }

    /**
     * 获取分类商品
     * @param Request $request
     * @return array
     */
    public function sort_goods(Request $request)
    {
        $data = $request->all();
        $shopModel = new ShopGoods();
        if (!empty($data['two_tid'])) {
            $shopData = $shopModel->where(['status' => 1, 'type' => 1, 'cid' => $data['cid'], 'two_tid' => $data['two_tid'], 'is_throw' => 0])->orderby('id', 'DESC')->get()->toArray();
            if (empty($shopData)) {
                return ['code' => 0, 'data' => '暂无商品'];
            } else {
                return ['code' => 1, 'data' => $shopData];
            }
        } else {
//            $ClassifyModel = new ShopGoodsClassify();
//            $classify = $ClassifyModel->where(['enabled' => 1, 'pid' => $data['cid']])->first();
            $shopData = $shopModel->where(['status' => 1, 'type' => 1, 'cid' => $data['cid'], 'is_throw' => 0])->orderby('id', 'DESC')->get()->toArray();
            if (empty($shopData)) {
                return ['code' => 0, 'data' => '暂无商品'];
            } else {
                return ['code' => 1, 'data' => $shopData];
            }
        }

    }

    /**
     * 源头厂家
     */
    public function factory()
    {
        return view('Home.index.factory');
    }

    /**
     * 厂家详情
     */
    public function factory_detail()
    {
        return view('Home.index.factory_detail');
    }

    /**
     * 厂家信息
     * @param Request $request
     * @return array
     */
    public function get_factory(Request $request)
    {
        $data = $request->all();
        $factoryModel = new Factory();
        switch ($data['class']) {
            case 'select':
                $factory = $factoryModel->where('status', 1)->orderBy('id', 'DESC')->get()->toArray();
                if (!empty($factory)) {
                    return ['code' => 1, 'data' => $factory];
                } else {
                    return ['code' => 0, 'data' => '暂无厂家'];
                }
                break;
            case 'find':
                if (empty($data['id'])) {
                    return ['code' => 0, 'data' => 'id有误'];
                }
                $detail = $factoryModel->where('id', $data['id'])->first();
                if (!empty($detail)) {
                    return ['code' => 1, 'data' => $detail];
                } else {
                    return ['code' => 0, 'data' => '厂家详情有误'];
                }
                break;
        }

    }

    /**
     * 导师
     */
    public function tutor()
    {

        return view('Home.index.teacher');
    }

    public function tutorIndex()
    {
        $tutorModel = new Tutor();
        $factory = $tutorModel->where('status', 1)->orderBy('id', 'DESC')->get()->toArray();
        if (!empty($factory)) {
            return ['code' => 1, 'data' => $factory];
        } else {
            return ['code' => 0, 'data' => '暂无导师'];
        }
    }

    //复投详情
    public function throw_details()
    {

        return view('Home.excellent.throw');
    }

    /*
     * 推客联盟
     */
    public function tuike()
    {


        return view('Home.index.tuike');
    }

    /*
    * 产品详情
    */
    public function tuike_det(Request $request)
    {
        $data = $request->all();

        return view('Home.index.tuike_det');
    }

    public function tuike_det_data(Request $request)
    {
        $data = $request->all();
        header("Content-type:application/json;charset=utf-8");
        $tuike_config = config("tuike");

        $goodsId = isset($data["goodsId"]) ? $data["goodsId"] : "pdd";
        $source = isset($data["source"]) ? $data["source"] : "pdd";
        $shop_id = isset($data["shop_id"]) ? $data["shop_id"] : "";

        $user = session('home_user');
        $uid = $user->uid;

        $url = "http://api.act.jutuike.com/union/convert";
        $params = [
            "pub_id" => $tuike_config["pub_id"],
            "goodsId" => $goodsId,
            "source" => $source,
            "sid" => $shop_id . "_" . $uid,
        ];

        $response = httpRequest($url, "POST", $params);
        $arr_response = json_decode($response, true);
        if ($arr_response["code"] == 1) {
            $r_data = [
                "code" => 0,
                "msg" => $arr_response["msg"],
                "data" => $arr_response["data"],
            ];
        } else {
            $r_data = [
                "code" => 1,
                "msg" => $response["msg"],
                "data" => $arr_response["data"],
            ];
        }


        echo json_encode($r_data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /*
    * 推客联盟
    */
    public function tuike_list()
    {
        return view('Home.index.tuike_list');
    }

    /*
   * 推客联盟
   */
    public function tuike_data(Request $request)
    {

        header("Content-type:application/json;charset=utf-8");
        $tuike_config = config("tuike");
        $data = $request->all();


        $source = isset($data["source"]) ? $data["source"] : "pdd";
        $cat = isset($data["cat"]) ? $data["cat"] : "1";
        $page = isset($data["page"]) ? $data["page"] : 1;
        $page_size = isset($data["page_size"]) ? $data["page_size"] : 20;
        $url = "http://api.act.jutuike.com/union/query_goods";
        $params = [
            "pub_id" => $tuike_config["pub_id"],
            "source" => $source,
            "cat" => $cat,
            "page" => $page,
            "pageSize" => $page_size,
            "sub_share_rate" => "1",
        ];


        $response = httpRequest($url, "POST", $params);

        // Log::write(print_r($response,true));

        $arr_response = json_decode($response, true);
        if (!empty($arr_response["data"])) {
            foreach ($arr_response["data"] as $key => $val) {
                $arr_response["data"][$key]["commission"] = floor($val["commission"] * 0.3 * 100) / 100;
            }
            unset($val);
        }


        if ($arr_response["total_results"] == 0) {
            $re_data = [
                "code" => 1,
                "message" => "无更多内容",
                "data" => []
            ];
        } else {
            $re_data = [
                "code" => 0,
                "message" => "成功",
                "data" => [
                    "page_count" => ceil($arr_response["total_results"] / $page_size),
                    "count" => $arr_response["total_results"],
                    "list" => $arr_response["data"]
                ],
            ];
        }


        echo json_encode($re_data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /*
     * 供应链
     */
    public function supply()
    {
        return view('Home.supply.index');
    }

    /**
     * 供应链token
     */
    public function token()
    {
        $tokens = Token::where('id', 1)->first();
        $time = time();
        $url = "https://supplyapi.blkongjianzhan.com/api/NoAuth/access_token";
        $data = [
            'username' => 'shoumao',
            'password' => 'shoumao789',
        ];
        if ($tokens) {
            if ($time > $tokens['expire_time']) {
                $datas = httpRequest($url, 'post', $data);
                $res = json_decode($datas, true);
                if ($res['code'] == 1) {
                    $row = [
                        'access_token' => $res['data']['access_token'],
                        'expire_time' => $res['data']['expire_time'],
                    ];
                    Token::where('id', 1)->update($row);
                }
            }
        } else {
            $datas = httpRequest($url, 'post', $data);
            $res = json_decode($datas, true);
            if ($res['code'] == 1) {
                $row = [
                    'access_token' => $res['data']['access_token'],
                    'expire_time' => $res['data']['expire_time'],
                ];
                Token::create($row);
            }
        }

    }

    /**
     * 供应链分类
     */
    public function classification()
    {
        $url = "https://supplyapi.blkongjianzhan.com/api/Category/get_lis";
//        $token = Session::get('supply_token');
        $token = Token::where('id', 1)->first();
        $data = [
            'access_token' => $token['access_token'],
            'limit' => '20',
        ];
        $datas = httpRequest($url, 'post', $data);
        $arr_response = json_decode($datas, true);
        if ($arr_response["code"] == 1) {
            return ['code' => 1, 'data' => $arr_response["data"]];
        } else {
            return ['code' => 0, 'data' => $arr_response["message"]];
        }
    }

    /**
     * 供应链商品列表
     */
    public function goods_list(Request $request)
    {
        $data = $request->all();
        $url = "https://supplyapi.blkongjianzhan.com/api/goods/get_spuid_list_v2";
        $token = Token::where('id', 1)->first();
        $page = isset($data["page"]) ? $data["page"] : 1;
        $category_id = isset($data["category_id"]) ? $data["category_id"] : 1;
        $limit = isset($data["limit"]) ? $data["limit"] : 30;
        $data_res = [
            'access_token' => $token['access_token'],
            'category_id' => $category_id,
            'limit' => $limit,
            'page' => $page,
            'keywords' => $data['keyword'],
        ];
        $datas = httpRequest($url, 'post', $data_res);
        $arr_response = json_decode($datas, true);
        if ($arr_response["code"] == 1) {
//            foreach ($arr_response["data"]['data'] as $k => $v) {
//                $arr_response["data"]['data'][$k]['price'] = RETAIN_TWO($v['price'] + $v['price'] * 0.2);
//            }
            return ['code' => 1, 'data' => $arr_response["data"]];
        } else {
            return ['code' => 0, 'data' => $arr_response["message"]];
        }
    }

    /**
     * 商品详情页面
     */
    public function details()
    {
        return view('Home.supply.details');
    }

    /**
     * 商品详情
     */
    public function goods_details(Request $request)
    {
        $data = $request->all();
        $url = "https://supplyapi.blkongjianzhan.com/api/goods/get_sku_id_v2";
        $token = Token::where('id', 1)->first();
        $data_res = [
            'access_token' => $token['access_token'],
            'sku_id' => $data['goods_id'],
        ];
        $datas = httpRequest($url, 'post', $data_res);
        $arr_response = json_decode($datas, true);
        if ($arr_response["code"] == 1) {
            return ['code' => 1, 'data' => $arr_response["data"]];
        } else {
            return ['code' => 0, 'data' => $arr_response["message"]];
        }
    }

    /*
     * 商品规格
     */
    public function goods_spec(Request $request)
    {
        $data = $request->all();
        $url = "https://supplyapi.blkongjianzhan.com/api/Goods/get_skuId_info";
        $token = Token::where('id', 1)->first();
        $data_res = [
            'access_token' => $token['access_token'],
            'goods_id' => $data['goods_id'],
        ];
        $datas = httpRequest($url, 'post', $data_res);
        $arr_response = json_decode($datas, true);
        if ($arr_response["code"] == 1) {
            return ['code' => 1, 'data' => $arr_response["data"]];
        } else {
            return ['code' => 0, 'data' => $arr_response["message"]];
        }
    }

    /**
     * 复投商品
     */
    public function fu_index()
    {

        return view('Home.fu.index');
    }

    public function fu_list(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        if ($user['is_out'] == 1) {
            return ['code' => 0, 'data' => '未达到复投标准'];
        }
        $shopModel = new ShopGoods();
        $shopData = $shopModel->where(['status' => 1, 'type' => 1, 'cid' => $data['cid'], 'is_throw' => 1])->orderby('id', 'DESC')->get()->toArray();
        if (empty($shopData)) {
            return ['code' => 0, 'data' => '暂无商品'];
        } else {
            return ['code' => 1, 'data' => $shopData];
        }
    }

    /**
     * 供应链生成订单
     */
    public function order(Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        $address = Address::where(['uid' => $user['uid'], 'default' => 1])->first();
        if (!$address) {
            return ['code' => 0, 'data' => '请添加默认收货地址'];
        }
        $goods_order[] = [
            'supply_goods_id' => $data['goodsid'],
            'num' => $data['number'],
            'supply_sku_id' => $data['sku_id'],
            'actual_s_price' => $data['price'],
        ];
        $user_address = [
            'name' => $address['name'],
            'buyer_mobile_api' => $user['name'],
            'mobile' => $address['phone'],
            'address' => $address['address'],
            'full_address' => $address['province'] . $address['city'] . $address['district'],
        ];

        $url = "https://supplyapi.blkongjianzhan.com/api/order/create_order";
        $token = Token::where('id', 1)->first();
        $data_res = [
            'access_token' => $token['access_token'],
            'order_prodcot' => json_encode($goods_order, JSON_UNESCAPED_UNICODE),
            'order_recipient' => json_encode($user_address, JSON_UNESCAPED_UNICODE),
        ];
//        var_dump($data_res);exit;
        $datas = httpRequest($url, 'post', $data_res);
//        var_dump($datas);exit;
        $arr_response = json_decode($datas, true);
//        var_dump($arr_response);exit;
        if ($arr_response["code"] == 1) {
            return ['code' => 1, 'data' => $arr_response['data']["order_no"]];
        }
    }

    /**
     * 复投商品
     */
    public function supply_order()
    {

        return view('Home.member.supplyorder');
    }
    /**
     *供应链订单
     */
    public function my_order(Request $request){
        $data = $request->all();
        $user = session('home_user');
        $url = "https://supplyapi.blkongjianzhan.com/api/order/order_list";
        $token = Token::where('id', 1)->first();
        $page = isset($data["page"]) ? $data["page"] : 1;
        $page_size = isset($data["limit"]) ? $data["limit"] : 40;
        $data_res = [
            'access_token' => $token['access_token'],
            'buyer_mobile_api' => $user['name'],
            'page_size' => $page_size,
            'page' => $page,
        ];
        $datas = httpRequest($url, 'post', $data_res);
        $arr_response = json_decode($datas, true);
        if ($arr_response["code"] == 1) {
            return ['code' => 1, 'data' => $arr_response["data"]];
        } else {
            return ['code' => 0, 'data' => $arr_response["message"]];
        }
    }
    /**
     * 订单想起页面
     */

    public function  supply_details(){

        return view('Home.supply.order_details');
    }
    /**
     *订单详情
     */
    public function order_details(Request $request){
        $data = $request->all();
//        $user = session('home_user');
        $url = "https://supplyapi.blkongjianzhan.com/api/order/order_details";
        $token = Token::where('id', 1)->first();
        $data_res = [
            'access_token' => $token['access_token'],
            'order_no' => $data['order_no'],
        ];
        $datas = httpRequest($url, 'post', $data_res);
        $arr_response = json_decode($datas, true);
        if ($arr_response["code"] == 1) {
            return ['code' => 1, 'data' => $arr_response["data"]];
        } else {
            return ['code' => 0, 'data' => $arr_response["message"]];
        }
    }
}
